package com.czmh.etc.common.core.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * @描述：JwtUtil
 * @author： Seven.
 * @创建日期：2019年06月25日
 * @版本：1.0.0
 */
public class JwtUtil {
    private static Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    private static final String ENCODE_SECRET_KEY = "@UIsdf*73:09234;?.sdfhi{weyrn&jnn#33###$$RYW&^}:<sdf723b6bdfy2m_0234n41$";

    /**
     * token过期时间
     */
    public static final long EXPIRE_TIME = 1000 * 60 * 60 * 24 * 7;

    /**
     * 生成token
     *
     * @return
     */
    public static String createToken(String account) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(account + ENCODE_SECRET_KEY);
        return JWT.create()
                .withExpiresAt(date)
                .withClaim("account", account)
                .sign(algorithm);
    }

    /**
     * 校验token是否失效
     *
     * @param token
     * @param account
     * @return
     */
    public static boolean checkToken(String token, String account) {
        Algorithm algorithm = Algorithm.HMAC256(account + ENCODE_SECRET_KEY);
        JWTVerifier verifier = JWT.require(algorithm)
                .build();
        try {
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            logger.error("token校验失败：", e);
            return false;
        }

    }

    /**
     * 获取用户account
     *
     * @param token
     * @return
     */
    public static String getAccount(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("account").asString();
        } catch (JWTDecodeException e) {
            logger.error("获取账号失败：", e);
            return null;
        }
    }
}